package com.smartmedical.patient.userInquiry.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.smartmedical.common.security.utils.SecurityUtils;
import com.smartmedical.patient.userInquiry.domain.dto.param.EvaluateParam;
import com.smartmedical.patient.userInquiry.domain.entity.*;
import com.smartmedical.patient.userInquiry.domain.vo.*;
import com.smartmedical.patient.userInquiry.mapper.InquiryMapper;
import com.smartmedical.patient.userInquiry.service.InquiryService;
import com.smartmedical.patient.userInquiry.util.RsaCoder;
import com.smartmedical.system.api.model.LoginUser;
import io.swagger.models.auth.In;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

@Service
@DS("slave")
@Log4j2
public class InquiryServiceImpl implements InquiryService {
    @Autowired
    private InquiryMapper inquiryMapper;

    @Override
    public List<DoctorVo> findDoctorList(Integer deptId, Integer condition, Integer sortBy) {

        List<DoctorEntity> doctorEntities = inquiryMapper.doctorEntity(deptId);

        List<DoctorVo> doctorVos = new ArrayList<>();
        for (DoctorEntity entity : doctorEntities) {
            DoctorVo doctorVo = new DoctorVo();
            DoctorCharge doctorCharge = inquiryMapper.doctorCharge(entity.getDoctorId());
            doctorVo.setServicePrice(doctorCharge.getCost());
            doctorVo.setDoctorId(entity.getDoctorId());
            doctorVo.setDoctorName(entity.getName());
            doctorVo.setImagePic(entity.getImagePic());
            doctorVo.setJobTitle(entity.getJobTitle());
            doctorVo.setInauguralHospital(entity.getInauguralHospital());
            DoctorCommentCount doctored = inquiryMapper.doctorCommentCount(entity.getDoctorId());
            doctorVo.setPraiseNum(doctored.getPraiseNum());
            doctorVo.setCommentNum(doctored.getPraiseNum() + doctored.getBadNum());
            doctorVo.setBadNum(doctored.getBadNum());
            doctorVo.setPraise(doctorVo.getPraiseNum() / doctorVo.getCommentNum() + "");
            doctorVos.add(doctorVo);
        }
        if (condition == 1 || condition == 2 || condition == 3) {
            return doctorVos;
        } else if (doctorVos != null && !doctorVos.isEmpty()) {
            // 根据ServicePrice以倒序方式对列表进行排序
            Collections.sort(doctorVos, Comparator.comparing(DoctorVo::getServicePrice).reversed());
            return doctorVos;
        } else {
            // 如果列表为空，则返回空列表或其他适当的处理
            return new ArrayList<>();
        }

    }


    @Override
    public DoctorVo findDoctorInfo(Integer doctorId) {
        // 创建 DoctorVo 对象
        DoctorVo doctorVo = new DoctorVo();
        // 根据医生ID查询医生信息
        DoctorEntity doctorEntity = inquiryMapper.findDoctorInfo(doctorId);
        // 设置医生姓名
        doctorVo.setDoctorName(doctorEntity.getName());
        // 设置医生头像
        doctorVo.setImagePic(doctorEntity.getImagePic());
        // 设置职位
        doctorVo.setJobTitle(doctorEntity.getJobTitle());
        // 设置就职医院
        doctorVo.setInauguralHospital(doctorEntity.getInauguralHospital());
        // 创建 DoctorReceiveGiftVo 列表
        List<DoctorReceiveGiftVo> doctorReceiveGiftVos = new ArrayList<>();
        // 创建 CommentVo 列表
        List<CommentVo> commentVos = new ArrayList<>();
        // 查询医生评论数量
        DoctorCommentCount doctored = inquiryMapper.doctorCommentCount(doctorId);
        // 设置评论数和点赞数
        doctorVo.setCommentNum(doctored.getPraiseNum() + doctored.getBadNum());
        doctorVo.setPraiseNum(doctored.getPraiseNum());
        doctorVo.setBadNum(doctored.getBadNum());
        // 设置点赞率
        doctorVo.setPraise(doctorVo.getPraiseNum() / doctorVo.getCommentNum() + "");
        // 查询医生获得的礼物列表
        List<DoctorObtainGift> doctorObtainGifts = inquiryMapper.findDoctorObtainGift(doctorId);
        // 遍历礼物列表，为每个 DoctorReceiveGiftVo 设置收到的礼物数量和礼物的相关信息
        for (DoctorReceiveGiftVo doctorReceiveGiftVo : doctorReceiveGiftVos) {
            doctorReceiveGiftVo.setReceiveNum(doctorObtainGifts.size());
            for (DoctorObtainGift doctorObtainGift : doctorObtainGifts) {
                int giftId = doctorObtainGift.getGiftId();
                // 根据礼物ID查询礼物信息
                Gift gift = inquiryMapper.giftVo(giftId);
                // 设置礼物的价值、名称、图片和意义
                doctorReceiveGiftVo.setWorth(gift.getWorth());
                doctorReceiveGiftVo.setGiftName(gift.getName());
                doctorReceiveGiftVo.setGiftPic(gift.getPic());
                doctorReceiveGiftVo.setMeaning(gift.getMeaning());
            }
            // 将 DoctorReceiveGiftVo 添加到列表中
            doctorReceiveGiftVos.add(doctorReceiveGiftVo);
        }
        // 查询医生的评价列表
        List<DoctorEvaluate> doctorEvaluates = inquiryMapper.doctorEvaluate(doctorId);
        // 遍历评价列表，为每个 CommentVo 设置评论时间、内容和评论者的昵称和头像信息
        for (CommentVo commentVo : commentVos) {
            for (DoctorEvaluate doctorEvaluate : doctorEvaluates) {
                int userId = doctorEvaluate.getUserId();
                commentVo.setCommentTime(doctorEvaluate.getCreateTime());
                commentVo.setContent(doctorEvaluate.getEvaluate());
                UserEntity userEntity = inquiryMapper.userEntity(userId);
                commentVo.setNickName(userEntity.getUserName());
                commentVo.setHeadPic(userEntity.getHeadPic());
            }
            // 将 CommentVo 添加到列表中
            commentVos.add(commentVo);
        }
        // 设置评论列表和获得礼物列表给 DoctorVo 对象，并返回 DoctorVo 对象
        return doctorVo;
    }

    @Override
    public String consultDoctor(int doctorId) {
        //鉴权逻辑，验证用户身份，可根据需要进行处理
        String doctorUserName = inquiryMapper.getDoctorIMAccount(doctorId);
        try {
            // 将医生IM账号转换为Base64
            String base64DoctorUserName = RsaCoder.encryptByPublicKey(doctorUserName);

            // 使用RSA私钥解密Base64格式的doctorIMAccount
            String decryptedDoctorUserName = RsaCoder.decryptByPublicKey(base64DoctorUserName);

            // 出参中返回解密后的doctorIMAccount
            return decryptedDoctorUserName;
        } catch (Exception e) {
            e.printStackTrace();
            return "咨询失败";
        }
    }


    @Override
    public String followDoctor(int doctorId) {
        if (doctorId == 0) {
            throw new RuntimeException("医生ID不能为空");
        } else {
            // 将 DoctorObtainGift 对象插入到数据库
            UserDoctorFollow userDoctorFollow = new UserDoctorFollow();
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userid = loginUser.getUserid();
            userDoctorFollow.setUserId(userid);
            userDoctorFollow.setDoctorId(doctorId);
            userDoctorFollow.setCreateTime(new Date());
            return inquiryMapper.followDoctor(userDoctorFollow);
        }
    }

    @Override
    public String cancelFollow(int doctorId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();
        // 查看当前用户是否关注了该医生
        if (inquiryMapper.cancelFollow(userid, doctorId)) {
            return "取消关注成功";
        } else {
            return "取消关注失败";
        }
    }

    /**
     * 结束问诊
     *
     * @param recordId 问诊记录ID
     */
    @Override
    public void endInquiry(int recordId) {
        // 检查问诊记录ID是否为空
        if (recordId == 0) {
            throw new RuntimeException("问诊记录ID不能为空");
        }
        // 结束问诊，获取问诊记录信息
        InquiryRecord inquiryRecord = inquiryMapper.startInquiryRecord(recordId, 1);
        //结束问诊，修改问诊记录状态
        inquiryMapper.endInquiry(recordId);
        if (inquiryRecord == null) {
            throw new RuntimeException("没有找到该问诊记录");
        }

        // 获取医生问诊次数信息
        DoctorAskCount doctorAskCount = inquiryMapper.getDoctorAskCount(inquiryRecord.getDoctorId());

        // 如果医生问诊次数信息为空，表示医生首次问诊，添加新的记录
        if (doctorAskCount == null) {
            doctorAskCount = new DoctorAskCount();
            doctorAskCount.setDoctorId(inquiryRecord.getDoctorId());
            doctorAskCount.setNumber(1);
            doctorAskCount.setUpdateTime(new Date());
            doctorAskCount.setCreateTime(new Timestamp(new Date().getTime()));
            // 添加医生问诊次数记录到数据库
            inquiryMapper.addDoctorAskCount(doctorAskCount);
        } else {
            // 如果医生已有问诊次数记录，增加次数并更新信息
            doctorAskCount.setNumber(doctorAskCount.getNumber() + 1);
            doctorAskCount.setUpdateTime(new Date());

            // 更新医生问诊次数记录到数据库
            inquiryMapper.updDoctorAskCount(doctorAskCount);
        }
    }


    /**
     * 评价问诊
     *
     * @param evaluateParam
     */
    @Override
    public void evaluateInquiry(EvaluateParam evaluateParam) {
        if (evaluateParam.getEvaluate() == null) {
            throw new RuntimeException("评价内容不能为空");
        } else {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userid = loginUser.getUserid();
            // 将 DoctorEvaluate 对象插入到数据库
            inquiryMapper.insert(evaluateParam, userid);
        }
    }

    /**
     * 送礼物
     *
     * @param inquiryRecordId
     * @param giftId
     */
    @Override
    public void updEvaluateInquiry(int inquiryRecordId, int giftId) {
        // 检查礼物ID是否为空
        if (giftId == 0) {
            throw new RuntimeException("礼物ID不能为空");
        }

        // 获取问诊记录信息
        InquiryRecord inquiryRecord = inquiryMapper.inquiryRecord(inquiryRecordId);

        // 获取医生获得礼物信息
        DoctorObtainGift doctorObtainGift = inquiryMapper.doctorObtainGift(inquiryRecord.getDoctorId());

        // 如果医生礼物信息为空或者礼物ID不一致，创建新的医生礼物信息
        if (doctorObtainGift == null || doctorObtainGift.getGiftId() != giftId) {
            doctorObtainGift = new DoctorObtainGift();
            doctorObtainGift.setDoctorId(inquiryRecord.getDoctorId());
            doctorObtainGift.setGiftId(giftId);
            doctorObtainGift.setNumber(1);
            doctorObtainGift.setCreateTime(new Timestamp(new Date().getTime()));
            doctorObtainGift.setUpdateTime(new Timestamp(new Date().getTime()));

            // 添加医生礼物信息到数据库
            inquiryMapper.addDoctorObtainGift(doctorObtainGift);
        }
        // 如果礼物ID一致且医生已经获得过礼物，增加礼物数量并更新信息
        else if (doctorObtainGift.getGiftId() == giftId && doctorObtainGift.getNumber() > 0) {
            doctorObtainGift.setNumber(doctorObtainGift.getNumber() + 1);
            doctorObtainGift.setUpdateTime(new Date());

            // 更新医生礼物信息到数据库
            inquiryMapper.updDoctorObtainGift(doctorObtainGift);
        }
    }


    /**
     * 查询当前问诊
     *
     * @return
     */
    @Override
    public InquiryRecordVo findCurrentInquiryRecord() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 获取用户ID
        Long userid = loginUser.getUserid();
        // 根据用户ID查询当前咨询记录
        InquiryRecordVo inquiryRecordVo = inquiryMapper.findCurrentInquiryRecord(userid);
        // 如果咨询记录的状态为3
        if (inquiryRecordVo.getStatus() == 3) {
            // 设置评价状态为1
            inquiryRecordVo.setEvaluateStatus(1);
        }
        // 返回咨询记录视图对象
        return inquiryRecordVo;

    }

    @Override
    public List<InquiryRecordVo> findHistoryInquiryRecord() {
        List<InquiryRecordVo> inquiryRecordVos = inquiryMapper.findHistoryInquiryRecord();
        return inquiryRecordVos;
    }

    @Override
    public List<InquiryDetailsRecordVo> findInquiryRecordList(int inquiryId) {
        if (inquiryId == 0) {
            throw new RuntimeException("问诊记录ID不能为空");
        } else {
            // 查询问诊记录列表
            List<ChatContentEntity> list = inquiryMapper.findInquiryRecordList(inquiryId);

            List<InquiryDetailsRecordVo> inquiryRecordVo =  createInquiryRecordVo(inquiryId, list);

            return inquiryRecordVo;
        }
    }

    private List<InquiryDetailsRecordVo> createInquiryRecordVo(int inquiryId, List<ChatContentEntity> list) {
        List<InquiryDetailsRecordVo> inquiryRecordVos = new ArrayList<>();
        for (ChatContentEntity chatContentEntity : list) {
            InquiryDetailsRecordVo inquiryDetailsRecordVo = new InquiryDetailsRecordVo();
            Integer sendUserRole = chatContentEntity.getSendUserRole();

            // 获取接受者头像
            Integer acceptUserId = chatContentEntity.getAcceptUserId();
            String headPic = inquiryMapper.selectUserinfo(acceptUserId);
            //发送人头像
            Integer sendUserId = chatContentEntity.getSendUserId();
            String imagePic = inquiryMapper.selectDoctorinfo(sendUserId);

            if (sendUserRole == 1) {
                //接受者id（患者）
                inquiryDetailsRecordVo.setUserHeadPic(headPic);
                //发送人（医生）
                inquiryDetailsRecordVo.setDoctorHeadPic(imagePic);
                //接收
                inquiryDetailsRecordVo.setDirection(2);
            }else if (sendUserRole == 0){
                //接受者id（医生）
                inquiryDetailsRecordVo.setDoctorHeadPic(headPic);
                //发送人（患者）
                inquiryDetailsRecordVo.setUserHeadPic(imagePic);
                //发送
                inquiryDetailsRecordVo.setDirection(1);
            }
            //消息类型
            inquiryDetailsRecordVo.setMsgType(chatContentEntity.getMsgType());
            //消息内容
            inquiryDetailsRecordVo.setContent(chatContentEntity.getContent());
            //消息时间
            inquiryDetailsRecordVo.setAskTime(chatContentEntity.getCreateTime());

            inquiryRecordVos.add(inquiryDetailsRecordVo);
        }
        return inquiryRecordVos;
    }

    @Override
    public DoctorEvaluateVo findDoctorEvaluate(int recordId) {
        if (recordId == 0) {
            throw new RuntimeException("问诊记录ID不能为空");
        } else {
            // 查询医生的评价列表
            DoctorEvaluateVo doctorEvaluateVo = inquiryMapper.findDoctorEvaluate(recordId);
            return doctorEvaluateVo;
        }
    }

    @Override
    public List<GiftVo> findGiftList() {
        List<GiftVo> giftVos = inquiryMapper.findGiftList();
        return giftVos;
    }

    @Override
    public List<CommentVo> findDoctorEvaluateList(int doctorId) {
        if (doctorId == 0) {
            throw new RuntimeException("医生ID不能为空");
        } else {
            // 查询医生的评价列表
            List<CommentVo> commentVos = inquiryMapper.findDoctorEvaluateList(doctorId);
            return commentVos;
        }
    }

}
